package com.example.mythealthapp.food_grid

import android.app.Activity
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.MediaStore
import android.widget.AdapterView.OnItemClickListener
import android.widget.GridView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.FileProvider
import com.example.mythealthapp.R
import com.example.mythealthapp.bean.FoodBean
import com.example.mythealthapp.bean.FoodUtils
import kotlinx.android.synthetic.main.activity_food_grid.*
import java.io.File

class FoodGridActivity : AppCompatActivity() {

    val takephoto=1
    lateinit var imgUri : Uri
    lateinit var outputImage : File


    var gv: GridView? = null
    var mDatas: List<FoodBean>? = null
    private var adapter: FoodGridAdapter? = null


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_food_grid)

        btn_camera.setOnClickListener {
            outputImage=File(externalCacheDir,"output_image.jpg")
            if(outputImage.exists()){
                outputImage.delete()
            }
            outputImage.createNewFile()
            imgUri=if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.N){
                FileProvider.getUriForFile(this,"com.example.mythealthapp",outputImage)
            }else{
                Uri.fromFile(outputImage)
            }
            //启动手机中的相机
            val intent = Intent("android.media.action.IMAGE_CAPTURE")
            intent.putExtra(MediaStore.EXTRA_OUTPUT,imgUri)
            startActivityForResult(intent,takephoto)
        }


        gv = findViewById(R.id.food_grid_gv)
        //        数据源
        mDatas = FoodUtils.getAllFoodList()
        //        创建适配器对象
        adapter = mDatas?.let { FoodGridAdapter(this, it) }
        //        设置适配器
        gv!!.adapter = adapter
        setListener()
    }

    private fun setListener() {
        gv!!.onItemClickListener =
            OnItemClickListener { parent, view, position, id ->
                val foodBean: FoodBean = mDatas!![position]
                val intent = Intent(this@FoodGridActivity, FoodDescActivity::class.java)
                intent.putExtra("food", foodBean)
                startActivity(intent)
            }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when(requestCode){
            takephoto->{
                if(resultCode==Activity.RESULT_OK){
                    val intent=Intent(this,IdentifyActivity::class.java)
                    intent.putExtra("imguri",imgUri.toString())
                    startActivity(intent)
                }
            }
        }
    }
}
